package cn.smile.business.wechat.impl;

import cn.smile.bean.dto.wechat.WechatDevelopConfigDTO;
import cn.smile.bean.entity.wechat.WechatDevelopConfig;
import cn.smile.bean.form.wechat.develop.SaveDevConfigForm;
import cn.smile.business.wechat.IWeChatApiService;
import cn.smile.business.wechat.IWeChatDevConService;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.commons.exceptions.BusinessException;
import cn.smile.commons.response.MyResponseCode;
import cn.smile.repository.wechat.WechatDevelopConfigMapper;
import cn.smile.utils.BeanCopy;
import cn.smile.utils.UserUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Slf4j
@Service
public class WeChatDevConServiceImpl extends BaseServiceImpl<WechatDevelopConfigMapper, WechatDevelopConfig> implements IWeChatDevConService {
    @Resource
    private IWeChatApiService accountService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveConfig(SaveDevConfigForm form) {
        log.info("[WeChatDevConServiceImpl].[saveConfig] ------> 用户保存微信开发者配置 Start, form = {}", JSON.toJSONString(form));
        this.checkParams(form);
        boolean isInsert = Boolean.FALSE;
        WechatDevelopConfig entity = baseMapper.selectOne(new QueryWrapper<WechatDevelopConfig>().lambda().eq(WechatDevelopConfig::getDeleted, Boolean.FALSE).eq(WechatDevelopConfig::getUserId, UserUtil.getUserInfo().getId()));
        if (ObjectUtils.isEmpty(entity)) {
            isInsert = Boolean.TRUE;
            entity = new WechatDevelopConfig();
            entity.setUserId(UserUtil.getUserInfo().getId());
        }
        entity.setEnableFlag(form.getEnableFlag());
        entity.setAppId(form.getAppId());
        entity.setAppSecret(form.getAppSecret());
        boolean flag;
        if (isInsert) {
            flag = super.create(entity);
        } else {
            flag = super.update(entity);
        }
        log.info("[WeChatDevConServiceImpl].[saveConfig] ------> 用户保存微信开发者配置 End, flag = {}", flag);
        return flag;
    }

    @Override
    public WechatDevelopConfigDTO getConfigByUser(String userId) {
        log.info("[WeChatDevConServiceImpl].[saveConfig] ------> 查询用户微信公众号配置 Start, userId = {}", userId);
        WechatDevelopConfig base = baseMapper.selectOne(new QueryWrapper<WechatDevelopConfig>().lambda().eq(WechatDevelopConfig::getDeleted, Boolean.FALSE).eq(WechatDevelopConfig::getUserId, userId));
        WechatDevelopConfigDTO entity = BeanCopy.copyBean(base, WechatDevelopConfigDTO.class);
        if (!ObjectUtils.isEmpty(base)) {
            entity.setEnableFlagString(base.getEnableFlag() ? "true" : "false");
        }
        log.info("[WeChatDevConServiceImpl].[saveConfig] ------> 查询用户微信公众号配置 End");
        return entity;
    }

    @Override
    public Boolean getMyConfigStatus() {
        log.info("[WeChatDevConServiceImpl].[getMyConfigStatus] ------> 查询我的公众号配置状态 Start");
        boolean flag = Boolean.FALSE;
        WechatDevelopConfigDTO config = this.getConfigByUser(UserUtil.getUserInfo().getId());
        if (!ObjectUtils.isEmpty(config) && !ObjectUtils.isEmpty(config.getEnableFlag())) {
            flag = config.getEnableFlag();
        }
        log.info("[WeChatDevConServiceImpl].[getMyConfigStatus] ------> 查询我的公众号配置状态 End");
        return flag;
    }

    @Override
    public WechatDevelopConfigDTO getConfigByAppId(String appId) {
        log.info("[WeChatDevConServiceImpl].[getConfigByAppId] ------> 通过微信AppID查询配置信息 Start, appId = {}", appId);
        WechatDevelopConfig base = baseMapper.selectOne(new QueryWrapper<WechatDevelopConfig>().lambda().eq(WechatDevelopConfig::getDeleted, Boolean.FALSE).eq(WechatDevelopConfig::getAppId, appId));
        if (ObjectUtils.isEmpty(base)) {
            throw new BusinessException(MyResponseCode.RESULT_DATA_NONE);
        }
        WechatDevelopConfigDTO entity = BeanCopy.copyBean(base, WechatDevelopConfigDTO.class);
        log.info("[WeChatDevConServiceImpl].[getConfigByAppId] ------> 通过微信AppID查询配置信息 End");
        return entity;
    }

    @Override
    public List<WechatDevelopConfig> getALlEnableConf() {
        log.info("[WeChatDevConServiceImpl].[getALlEnableConf] ------> 查询全部启用配置用户 Start");
        List<WechatDevelopConfig> baseList = baseMapper.selectList(new QueryWrapper<WechatDevelopConfig>().lambda().eq(WechatDevelopConfig::getEnableFlag, Boolean.TRUE).eq(WechatDevelopConfig::getDeleted, Boolean.FALSE));
        log.info("[WeChatDevConServiceImpl].[getALlEnableConf] ------> 查询全部启用配置用户 End");
        return baseList;
    }

    /**
     * 检查参数
     *
     * @param form 微信公众号保存开发者接口参数
     */
    private void checkParams(SaveDevConfigForm form) {
        if (form.getEnableFlag()) {
            this.accountService.getAccessToken(form.getAppId(), form.getAppSecret(), Boolean.TRUE);
        }
    }
}
